<template>
  <view class="contract-preview">
    <!-- 头部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <text class="back-icon">‹</text>
      </view>
      <view class="title">合同</view>
    </view>

    <!-- 合同内容 -->
    <view class="contract-content">
      <!-- 合同标题 -->
      <view class="contract-title">
        <text>合同</text>
      </view>

      <!-- 分割线 -->
      <view class="divider"></view>

      <!-- 合同正文 -->
      <view class="contract-text">
        <text>{{ contractData.borrowerRealName }}（居民身份证号：{{ setText(contractData.borrowerRealIdCard) }}）欠 </text>
        <text class="highlight">{{ contractData.lenderName }}</text>
        <text>（居民身份证号：{{ setText(contractData.lenderIdCard) }}）</text>
        <text>人民币{{
          contractData.amountInWords
        }} （￥{{ contractData.contractAmount }}），欠款期限为
        </text>
        <text class="highlight">{{ contractData.startDate }}</text>至
        <text class="highlight">{{ contractData.endDate }}</text>
        <text>，承诺按年化利率</text>
        <text class="highlight">{{ contractData.annualRate }}%</text>
        <text>计息支付利息，于到期日偿还本息</text>
        <text class="highlight">{{ contractData.contractAmount }}</text>
        <text>元</text>
      </view>

      <!-- 合同信息列表 -->
      <view class="contract-infos">
        <view class="info-item">
          <text class="label">编号</text>
          <text class="value">{{ contractData.contractNumber }}</text>
        </view>

        <view class="info-item">
          <text class="label">合同原因</text>
          <text class="value">{{ contractData.contractReason }}</text>
        </view>

        <view class="info-item" @click="showAgreementDetail">
          <text class="label">相关协议</text>
          <text class="value">查看详情</text>
          <text class="arrow">›</text>
        </view>
        <template v-if="contractData.borrowerType == 'lender'">
          <view class="info-item">
            <text class="label">出借人</text>
            <text class="value">{{ contractData.lenderName }}</text>
          </view>
          <view class="info-item-detail">
            <text class="sub-label">身份证：{{ setText(contractData.lenderIdCard) }}</text>
          </view>
        </template>
        <template v-else>
          <view class="info-item">
            <text class="label">借款人</text>
            <text class="value">{{ contractData.borrowerRealName }}</text>
          </view>
          <view class="info-item-detail">
            <text class="sub-label">身份证：{{ setText(contractData.borrowerRealIdCard) }}</text>
          </view>
        </template>


        <template v-if="[1, 2].includes(contractData.status) && contractData.status !== 6">
          <view class="" v-if="contractData.borrowerType == 'lender'">
            <view class="info-item">
              <text class="label required">借款人姓名</text>
              <view class="input-wrapper">
                <input class="form-input" v-model="contractData.borrowerRealName" placeholder="请输入借款人姓名" />
              </view>
            </view>

            <view class="info-item-detail">
              <text class="label required">借款人身份证号码</text>
              <view class="input-wrapper">
                <input class="form-input" v-model="contractData.borrowerRealIdCard" placeholder="请输入借款人身份证号码" />
              </view>
            </view>
          </view>
          <view v-else>
            <!-- 姓名 -->
            <view class="form-item">
              <text class="label required">出借人姓名</text>
              <view class="input-wrapper">
                <input class="form-input" v-model="contractData.lenderName" placeholder="请输入出借人姓名" />
              </view>
            </view>

            <!-- 身份证号码 -->
            <view class="form-item">
              <text class="label required">出借人身份证号码</text>
              <view class="input-wrapper">
                <input class="form-input" v-model="contractData.lenderIdCard" placeholder="请输入出借人身份证号码" />
              </view>
            </view>
          </view>
        </template>

        <template v-else>
          <view class="" v-if="contractData.borrowerType == 'lender'">
            <view class="info-item">
              <text class="label ">借款人姓名</text>
              <text class="value">{{ contractData.borrowerRealName }}</text>
            </view>
            <view class="info-item">
              <text class="label ">借款人身份证号码</text>
              <text class="value" style="text-align: right;">{{ setText(contractData.borrowerRealIdCard) }}</text>
            </view>
          </view>
          <view v-else>
            <view class="info-item">
              <text class="label">借款人姓名</text>
              <text class="value">{{ contractData.lenderName }}</text>
            </view>
            <view class="info-item">
              <text class="label">借款人身份证号码</text>
              <text class="value" style="text-align: right;">{{ setText(contractData.lenderIdCard) }}</text>
            </view>
          </view>
        </template>
      </view>
      <view v-if="contractData.payStatus == 2 && contractData.status == 6" class="highlight">
        合同展期至 {{ contractData.extendEndDate }}
      </view>
      <!-- 系统服务费 -->
      <view class="service-fee">
        <text class="fee-text" @click="updateChangeFiles">系统签约服务费：{{ contractData.payAmount }} 元 </text>
      </view>
    </view>

    <!-- 支付按钮 -->
    <view class="payment-section" v-if="contractData.payStatus < 3">
      <button :class="{ 'disabled': contractData.status == 2 }" class="payment-btn " style="margin-bottom: 10px; "
        @click="handleSubmitIdentity" v-if="contractStatus == 2">
        {{ contractData.status == 2 ? '已提交' : '提交身份信息' }}
      </button>
      <button class="payment-btn" :class="{ 'loading': paymentStatus !== 'idle', 'disabled': paymentStatus !== 'idle' }"
        @click="handlePayment" :disabled="paymentStatus !== 'idle'">
        <view v-if="paymentStatus === 'idle'">
          微信支付( {{ contractData.payAmount }} 元)
        </view>
        <view v-else-if="paymentStatus === 'loading'" class="loading-text">
          <text class="loading-icon">⏳</text>
          获取支付信息...
        </view>
        <view v-else-if="paymentStatus === 'authorizing'" class="loading-text">
          <text class="loading-icon">🔐</text>
          正在授权...
        </view>
        <view v-else-if="paymentStatus === 'paying'" class="loading-text">
          <text class="loading-icon">💳</text>
          支付中...
        </view>
        <view v-else-if="paymentStatus === 'success'" class="success-text">
          <text class="success-icon">✅</text>
          支付成功
        </view>
        <view v-else>
          微信支付( {{ contractData.payAmount }} 元)
        </view>
      </button>
      <button class="payment-btn " style="margin-top: 10px;" @click="handleShare" v-if="!contractStatus">
        分享
      </button>
    </view>

    <!-- 自定义支付确认弹窗 -->
    <view class="modal-overlay" v-if="!contractStatus && !payCode && contractData.payStatus == 1 && showPaymentModal">
      <view class="modal-content" @click.stop>
        <view class="modal-title">是否支付签约费用?</view>
        <view class="modal-buttons">
          <button class="modal-btn cancel-btn" @click="confirmSelfPayment">由我支付</button>
          <button class="modal-btn confirm-btn" @click="confirmOtherPayment">对方支付</button>
        </view>
      </view>
    </view>

    <!-- 分享指引弹窗 -->
    <view class="tui-alert-mask" :class="[showShareGuide ? 'tui-alert-mask-show' : '']">
      <view :style="{ width: width ? width : '100%' }" style="position: absolute;top: 0;right: 0;">
        <view>
          <image src="/static/point_bg.png" style="width: 100%;" mode="widthFix" />
        </view>
        <view @click="showShareGuide = false" style="text-align: center;">
          <image src="/static/point_btn.png" style="width: 60%;" mode="widthFix" />
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { onLoad, onUnload, onShow } from "@dcloudio/uni-app";
import { ref, onMounted } from "vue";
import request from "@/api/request.js";
import { setPageShareConfig } from '@/utils/share';
import { PaymentManager } from '@/utils/paymentManager.js';
import { isInWechat, parseUrlParams } from '@/utils/payment.js';

const contractNumber = ref("");
const contractData = ref({});
const contractStatus = ref('');
const showPaymentModal = ref(false);
const showShareGuide = ref(false);
const paymentStatus = ref('idle'); // 支付状态
const payCode = ref('');
// 支付管理器实例
let paymentManager = null;

onLoad(async (options) => {
  // 接收从上一页传递的合同数据
  if (options.contractNumber) {
    contractNumber.value = options.contractNumber;
    contractStatus.value = options.contractStatus || '';
    await getContractData();

    // 解析完整URL参数，包括查询字符串和hash中的参数
    const urlParams = parseUrlParams();
    // 合并页面options和完整URL参数
    const mergedParams = {
      ...options,
      ...urlParams
    };
    // 检查是否需要初始化支付管理器
    // 只在存在微信授权回调参数 (code, state) 时初始化
    const hasAuthCallback = mergedParams.code || mergedParams.state;
    payCode.value = mergedParams.code || '';
    if (hasAuthCallback) {
      console.log('初始化支付管理器 - 授权回调:', { code: mergedParams.code, state: mergedParams.state });
      initializePaymentManager(mergedParams);
    } else {
      console.log('跳过支付管理器初始化 - 无授权回调参数');
    }
  } else {
    console.error('缺少合同编号参数');
  }
});

uni.$on('update', (data) => {
  console.log('触发更新后')
  getContractData();
})

onUnload(() => {
  // 清理支付管理器
  if (paymentManager) {
    paymentManager.destroy();
    paymentManager = null;
  }
});


/**
 * 初始化支付管理器
 */
function initializePaymentManager(pageOptions) {
  // 防止重复初始化
  if (paymentManager) {
    console.log('支付管理器已存在，跳过重复初始化');
    return;
  }

  paymentManager = new PaymentManager({
    contractNumber: contractNumber.value,
    contractData: contractData.value,
    onStatusChange: (status, oldStatus) => {
      paymentStatus.value = status;
      console.log(`支付状态变更: ${oldStatus} -> ${status}`);
    },
    onSuccess: (result) => {
      console.log('支付成功:', result);
      // 可以在这里添加支付成功后的额外处理
    },
    onError: (error) => {
      console.error('支付失败:', error);
      // 可以在这里添加支付失败后的额外处理
    },
    onCancel: (error) => {
      console.log('支付取消:', error);
      // 可以在这里添加支付取消后的额外处理
    }
  });

  // 初始化支付管理器（处理授权回调等）
  // 合并页面参数和当前URL参数，确保获取最新的授权参数
  const urlParams = parseUrlParams();
  const mergedOptions = {
    ...pageOptions,
    ...urlParams
  };

  console.log('初始化支付管理器 - 合并参数:', mergedOptions);
  paymentManager.initialize(mergedOptions);
}

// 基本页面分享配置
function setupPageShare() {
  // 构建完整的分享链接
  const fullShareLink = 'https://www.stellargang.cn/h5/#/pages/borrow/contractPreview?contractNumber=' + contractNumber.value + '&contractStatus=2';

  const shareConfig = {
    title: '您有一份协议待签署',
    desc: '我在吏简给您发起了急速借条，快来确认吧！',
    imgUrl: 'https://www.stellargang.cn/h5/static/logo.png',
    link: fullShareLink
  };

  console.log('设置分享配置:', shareConfig);

  // 1. 首先设置页面级分享配置
  setPageShareConfig(shareConfig);

  // 2. 确保分享配置立即生效
  if (typeof initWxShare === 'function') {
    const initResult = initWxShare(shareConfig);
    console.log('直接调用initWxShare结果:', initResult);
  }

  // 3. 安全地获取App实例并调用setWechatShare方法作为额外保障
  try {
    // 在uni-app中，可以通过getApp()获取App实例
    const appInstance = getApp();

    if (appInstance && appInstance.setWechatShare) {
      console.log('调用App实例的setWechatShare方法');
      // 直接传入shareConfig参数，确保使用正确的链接
      appInstance.setWechatShare(shareConfig);
    } else {
      console.log('无法获取App实例或setWechatShare方法不存在');
    }
  } catch (error) {
    console.error('调用App实例方法时出错:', error);
  }

  // 4. 添加额外的日志验证最终配置
  setTimeout(() => {
    const currentConfig = getCurrentShareConfig();
    console.log('当前生效的分享配置:', currentConfig);
  }, 500);
}

const setText = (idCard) => {
  let text = "";
  if (idCard) {
    // 只显示前四位和后四位，中间*显示
    text += " " + idCard.slice(0, 1) + "************" + idCard.slice(-1);
  }
  return text;
};

const getContractData = async () => {
  uni.showLoading({
    title: "加载中...",
  });

  try {
    const res = await request.get("/api/contracts/number/" + contractNumber.value);

    if (res.code === 200) {
      contractData.value = res.data;

      // 更新支付管理器的合同数据
      if (paymentManager) {
        paymentManager.updateContractData(contractData.value);
      }

      if (contractData.value.status == 1) {
        showPaymentModal.value = true;
      }

      setTimeout(() => {
        setupPageShare();
      }, 800);
    }
  } catch (err) {
    uni.showToast({
      title: err.message || "获取合同数据失败",
      icon: "none",
    });
  } finally {
    uni.hideLoading();
  }
};

function goBack() {
  // 判断是否存在历史路由 
  const pages = getCurrentPages();
  if (pages.length > 1) {
    uni.navigateBack();
  } else {
    uni.switchTab({
      url: '/pages/home/index'
    });
  }
}

async function handleSubmitIdentity() {
  // 检查是否已提交身份信息
  if (contractData.value.status == 1) {
    // 检查是否填写了必要信息
    let success = await updateContractData();
    if (success) {
      uni.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000
      });
      // 刷新合同数据
      await getContractData();
    }
  }
}


function showAgreementDetail() {
  // 统一跳转到文件预览页面
  const fileUrl = 'https://www.stellargang.cn/files/' + contractData.value.contractFile;
  const officeOnlineURL = `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(fileUrl)}`;
  console.log(contractData.value.contractFile)
  uni.navigateTo({
    url: '/pages/borrow/webview?url=' + officeOnlineURL
  });
}

/**
 * 处理支付按钮点击
 */
async function handlePayment() {
   const userInfo = uni.getStorageSync("userInfo");
  //  判断是否实名
  if (userInfo.status !==3) {
     // 弹窗提示 点击确认去认证
    uni.showModal({
      title: '提示',
      content: '您还未实名认证，是否前往认证？',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/mine/profile'
          });
        }
      }
    });
    return 
  }
  uni.showLoading({
    title: '正在加载中...',
    mask: true
  });
  let success = await updateContractData();
  if (!success) {
    uni.hideLoading();
    return;
  }
  // 如果支付管理器未初始化，进行懒加载初始化
  if (!paymentManager) {
    initializePaymentManager({
      contractNumber: contractNumber.value
    });
  }
  // 使用支付管理器处理支付
  paymentManager.startPayment();
}

// 更新合同数据
async function updateContractData() {
  //判断字段是否为空
  if (!contractData.value.borrowerRealName || !contractData.value.borrowerRealIdCard || !contractData.value.lenderName || !contractData.value.lenderIdCard) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none',
      duration: 2000
    });
    return;
  }
  const res = await request.put("/api/contracts/updateParties", {
    ...contractData.value,
    contractId: contractData.value.id,
  });
  if (res) {
    return true
  }
}
function confirmSelfPayment() {
  showPaymentModal.value = false;
}

async function confirmOtherPayment() {
  showPaymentModal.value = false;
  // 出现分享指引
  showShareGuide.value = true;
}

async function handleShare() {
  // 检查是否在微信环境中
  if (!isInWechat()) {
    uni.showToast({
      title: '请在微信中打开',
      icon: 'none',
      duration: 2000
    });
    return;
  }
  showShareGuide.value = true;
}
</script>

<style scoped lang="scss">
.contract-preview {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  height: 88rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 40rpx;
  color: #333;
  font-weight: bold;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.contract-content {
  flex: 1;
  margin: 20rpx;
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
}

.contract-title {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  margin-bottom: 30rpx;
}

.contract-title text {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
}

.contract-seal {
  position: absolute;
  right: 0;
  width: 120rpx;
  height: 120rpx;
}

.divider {
  height: 2rpx;
  background: linear-gradient(to right, #667eea, #764ba2);
  margin-bottom: 40rpx;
}

.contract-text {
  line-height: 2;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 40rpx;
  text-align: justify;
}

.highlight {
  color: #667eea;
  font-weight: bold;
}

.contract-infos {
  margin-bottom: 40rpx;
}

.info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 25rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 28rpx;
  color: #666;
  min-width: 140rpx;
}

.value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  text-align: right;
  margin-right: 10rpx;
}

.arrow {
  font-size: 32rpx;
  color: #ccc;
}

.info-item-detail {}

.sub-label {
  font-size: 24rpx;
  color: #999;
}

.service-fee {
  text-align: right;
  margin-top: 20rpx;
}

.fee-text {
  font-size: 26rpx;
  color: #667eea;
}

.payment-section {
  padding: 30rpx;
  background: #fff;
}

.payment-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 44rpx;
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
}

.payment-btn:active {
  opacity: 0.8;
}

.payment-btn.loading {
  background: linear-gradient(135deg, #a0a0a0 0%, #808080 100%);
  cursor: not-allowed;
}

.payment-btn.disabled {
  opacity: 0.6;
  pointer-events: none;
}

.loading-text {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
}

.loading-icon {
  font-size: 28rpx;
  animation: pulse 1.5s ease-in-out infinite;
}

.success-text {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
}

.success-icon {
  font-size: 28rpx;
  animation: bounce 0.6s ease-in-out;
}

@keyframes pulse {

  0%,
  100% {
    opacity: 1;
  }

  50% {
    opacity: 0.5;
  }
}

@keyframes bounce {

  0%,
  20%,
  60%,
  100% {
    transform: translateY(0);
  }

  40% {
    transform: translateY(-10rpx);
  }

  80% {
    transform: translateY(-5rpx);
  }
}

/* 自定义弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  width: 560rpx;
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  margin: 0 30rpx;
}

.modal-title {
  padding: 60rpx 40rpx 40rpx;
  text-align: center;
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.modal-buttons {
  display: flex;
  border-top: 1rpx solid #e5e5e5;
}

.modal-btn {
  flex: 1;
  height: 100rpx;
  border: none;
  background: #fff;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.modal-btn:active {
  background: #f5f5f5;
}

.cancel-btn {
  color: #999;
}

.cancel-btn::after {
  content: '';
  position: absolute;
  right: 0;
  top: 20rpx;
  bottom: 20rpx;
  width: 1rpx;
  background: #e5e5e5;
}

.confirm-btn {
  color: #007AFF;
  font-weight: 500;
}

/* 表单项 */
.form-item {
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.form-item:last-child {
  border-bottom: none;
}

.label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  min-width: 200rpx;
  margin-right: 20rpx;
  margin-bottom: 0;
}

.label.required::after {
  content: "*";
  color: #ff4757;
  margin-left: 4rpx;
}

.input-wrapper {
  display: flex;
  align-items: center;
  position: relative;
  flex: 1;
  justify-content: flex-end;
}

.form-input {
  font-size: 28rpx;
  color: #333;
  background: transparent;
  border: none;
  outline: none;
  text-align: right;
  width: 100%;
}

.form-input::placeholder {
  color: #999;
}
</style>

<style scoped>
.tui-alert-mask1 {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  z-index: 99996;
  transition: all 0.3s ease-in-out;
  opacity: 0;
  visibility: hidden;
}

.tui-alert-mask {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1110;
  opacity: 0;
  outline: 0;
  text-align: center;
  -ms-transform: scale(1.185);
  transform: scale(1.185);
  backface-visibility: hidden;
  perspective: 2000upx;
  background: rgba(0, 0, 0, 0.6);
  transition: all 0.3s ease-in-out 0s;
  pointer-events: none;
}

.tui-alert-mask-show {
  opacity: 1;
  transition-duration: 0.3s;
  -ms-transform: scale(1);
  transform: scale(1);
  overflow-x: hidden;
  overflow-y: auto;
  pointer-events: auto;
}

.tui-alert-mask-show1 {
  visibility: visible;
  opacity: 1;
}
</style>
